<template>
  <div class="track-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="选择状态" @change="handleStatusChange">
              <!-- 配送员只能选择运输中和已送达两个状态 -->
              <el-option label="运输中" :value="4" />
              <el-option label="已送达" :value="5" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="时间" prop="timestamp">
            <el-date-picker
              v-model="formData.timestamp"
              type="datetime"
              placeholder="选择时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="位置" prop="location">
        <div class="location-input-group">
          <el-input
            v-model="formData.location"
            placeholder="点击地图选择位置或手动输入"
            clearable
            readonly
          />
          <el-button type="primary" @click="showMapDialog = true">
            <el-icon><Location /></el-icon>
            地图选择
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          提交轨迹
        </el-button>
        <el-button @click="handleCancel">
          取消
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 地图选择对话框 -->
    <el-dialog
      v-model="showMapDialog"
      title="选择位置"
      width="80%"
      :before-close="handleMapCancel"
    >
      <MapSelector
        :order-data="props.orderData"
        :existing-tracks="props.existingTracks"
        @location-selected="handleLocationSelected"
        @cancel="handleMapCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Location } from '@element-plus/icons-vue'
import MapSelector from './MapSelector.vue'

interface TrackActivity {
  id?: string
  content: string
  timestamp: string
  type: string
  color: string
  location: string
  operator?: string
  remark?: string
  status: number
  latitude?: number
  longitude?: number
}

interface Props {
  orderData?: {
    senderAddress: string
    recipientAddress: string
    senderCoords?: [number, number]
    recipientCoords?: [number, number]
  }
  existingTracks?: TrackActivity[]
}

interface Emits {
  (e: 'submit', trackData: Omit<TrackActivity, 'id'>): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const submitting = ref(false)
const showMapDialog = ref(false)

// 统一的表单数据定义
const formData = reactive({
  status: 4, // 默认为运输中
  timestamp: new Date().toISOString(),
  location: '',
  remark: '',
  coordinates: null as [number, number] | null // 添加坐标存储
})

// 状态配置
const statusConfig = {
  1: { type: 'info', color: '#909399', content: '已下单' },
  2: { type: 'primary', color: '#409EFF', content: '待揽件' },
  3: { type: 'primary', color: '#409EFF', content: '已揽件' },
  4: { type: 'warning', color: '#E6A23C', content: '运输中' },
  5: { type: 'warning', color: '#E6A23C', content: '已送达' },
  6: { type: 'success', color: '#67C23A', content: '已签收' }
}

// 表单验证规则
const formRules: FormRules = {
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  timestamp: [
    { required: true, message: '请选择时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请选择位置信息', trigger: 'blur' },
    { min: 2, max: 100, message: '位置信息长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

// 状态变化处理
const handleStatusChange = (status: number) => {
  const config = statusConfig[status as keyof typeof statusConfig]
  if (config) {
    // 可以在这里设置默认的备注信息
  }
}

// 地图选择处理
const handleLocationSelected = (data: { address: string; coordinates: [number, number] }) => {
  formData.location = data.address
  formData.coordinates = data.coordinates // 保存坐标
  showMapDialog.value = false
  console.log('选择的地址:', data.address, '坐标:', data.coordinates)
}

const handleMapCancel = () => {
  showMapDialog.value = false
}

// 统一的提交处理函数
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!formData.location || !formData.coordinates) {
      ElMessage.warning('请选择位置')
      return
    }
    
    // 添加坐标验证
    if (!Array.isArray(formData.coordinates) || formData.coordinates.length !== 2) {
      ElMessage.error('坐标数据无效，请重新选择位置')
      console.error('无效的坐标数据:', formData.coordinates)
      return
    }
    
    const [longitude, latitude] = formData.coordinates
    if (typeof longitude !== 'number' || typeof latitude !== 'number') {
      ElMessage.error('坐标数据格式错误，请重新选择位置')
      console.error('坐标数据类型错误:', { longitude, latitude })
      return
    }
    
    submitting.value = true
    
    const config = statusConfig[formData.status as keyof typeof statusConfig]
    const currentOperator = localStorage.getItem('user_name') || '配送员'
    
    // 构建轨迹数据（包含坐标）
    const trackData: Omit<TrackActivity, 'id'> = {
      content: config.content,
      timestamp: formData.timestamp,
      type: config.type,
      color: config.color,
      location: formData.location,
      latitude: latitude, // 确保是数字
      longitude: longitude, // 确保是数字
      operator: currentOperator,
      remark: formData.remark || '',
      status: formData.status
    }
    
    console.log('TrackForm 坐标验证通过:', {
      coordinates: formData.coordinates,
      latitude: trackData.latitude,
      longitude: trackData.longitude
    })
    console.log('TrackForm 提交轨迹状态', formData.status)
    console.log('父组件收到的轨迹数据', trackData)
    
    emit('submit', trackData)
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查填写的信息')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  resetForm()
  emit('cancel')
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  formData.location = ''
  formData.remark = ''
  formData.coordinates = null
  formData.timestamp = new Date().toISOString()
}
</script>

<style scoped>
.track-form {
  background: #fafbfc;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e2e8f0;
}

.location-input-group {
  display: flex;
  gap: 8px;
}

.location-input-group .el-input {
  flex: 1;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>